<template>
  <div class='confirm-order-container'>
    <h2>确认订单</h2>
    <div class="step-container">
      <el-steps :active="0"
                finish-status="success"
                align-center>
        <el-step title="确认订单">
        </el-step>
        <el-step title="支付">
        </el-step>
        <el-step title="支付完成">
        </el-step>
      </el-steps>
    </div>

    <div class="delivery-address-container">
      <h2>
        收货地址
        <span @click="addAddressDialogVisible=true">添加地址</span>
      </h2>
      <div class="delivery-address-info">
        <p>
          <i>收货人：</i> {{choosenAddressData.recive_user}}
        </p>
        <p class="phone">
          <i>手机号：</i> {{choosenAddressData.phone}}
        </p>
        <p class="address">
          <i>收货地址：</i> {{choosenAddressData.province}} {{choosenAddressData.city}} {{choosenAddressData.area}} {{choosenAddressData.recive_addr}}
        </p>
        <span @click="chooseAddressDialogVisible=true"
              class="choose-address">选择地址</span>
      </div>
    </div>
    <div class="product-info-container">
      <h2>产品信息</h2>
      <ul class="product-info-list">
        <li class="info-list-item"
            v-for="(item, index) in productCart"
            :key="index">
          <img :src="item.product_img"
               alt="">
          <div class="product-detail-container">
            <div class="product-info">
              <p class="product-name">{{item.product_name}}</p>
              <p class="product-description">{{item.product_desc}}</p>
            </div>
            <div class="product-info flex-end">
              <span class="product-price">
                ￥{{item.product_price}}
              </span>
              <span class="product-num">数量：{{item.num}}</span>
            </div>

          </div>

        </li>
      </ul>
    </div>
    <div class="order-info-container">
      <div class="order-info total-price">
        <i>商品总额：</i>
        <span>￥{{totalPrice}}</span>
      </div>
      <div class="order-info transport-fee">
        <i>运费：</i>
        <span>到付</span>
      </div>
      <div class="order-info">
        <i>应付金额：</i>
        <span class="should-pay">￥{{actualPrice}}</span>
      </div>
    </div>
    <div class="rule-container">
      <el-checkbox v-model="isAgree">
      </el-checkbox>
      <span>
        我已经认真阅读并同意
        <a @click.prevent="rulePdfDialogVisible=true">《杭州市装配式建筑质量监管平台实施服务协议》</a>
      </span>
    </div>
    <div class="submit-order-container">
      <button :disabled="!isAgree"
              :class="{'disabled':!isAgree}"
              @click="submitOrder">提交订单</button>
    </div>
    <!-- 选择收货地址弹框 -->
    <el-dialog title="选择地址"
               :visible.sync="chooseAddressDialogVisible"
               width="500px">
      <el-row>
        <el-col>
          <ul class="choose-address-list">
            <li class="choose-address-item"
                v-for="(item, index) in addressList"
                :key="index">
              <el-checkbox @change="chooseAddress(item)"
                           v-model="item.choosen"
                           class="choose-checkbox">
              </el-checkbox>
              <div class="address-info"
                   :class="{'choosen':item.choosen}">
                <p class="recive-name">
                  {{item.recive_user}}
                  <span class="recive-phone">{{item.phone}}</span>
                </p>
                <p class="recive-address">
                  {{item.province}} {{item.city}} {{item.area}} {{item.recive_addr}}
                </p>
              </div>
            </li>
          </ul>
        </el-col>
      </el-row>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="chooseAddressDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="chooseReciveAddress">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加收货地址弹框 -->
    <el-dialog title="添加收货地址"
               width="500px"
               :visible.sync="addAddressDialogVisible">
      <el-form :model="addAddressForm"
               ref="addressForm"
               class="add-address-form"
               :rules="addAddressFormRules"
               label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="收货人"
                          prop="recive_user">
              <el-input v-model="addAddressForm.recive_user"
                        placeholder="请输入收货人">
              </el-input>
            </el-form-item>
            <el-form-item label="手机号"
                          prop="recive_phone">
              <el-input v-model="addAddressForm.recive_phone"
                        type="phone"
                        placeholder="请输入手机号">
              </el-input>
            </el-form-item>
            <el-form-item label="验证码"
                          prop="verify_code">
              <el-input v-model="addAddressForm.verify_code"
                        class="get-verify-code"
                        placeholder="请输入验证码">
                <el-button slot="append"
                           @click="getVerifyCode"
                           :disabled="verifyCodeDisabled"
                           :class="{'disabled':verifyCodeDisabled}"
                           type="primary">{{verifyCodeBtnText}}</el-button>
              </el-input>
            </el-form-item>
            <el-form-item label="选择地址">

              <el-cascader placeholder="请选择收货地址"
                           @change="locationCascader"
                           v-model="addAddressForm.address"
                           class="choose-location-cascader"
                           :options="addressOptions">
              </el-cascader>
            </el-form-item>
            <el-form-item label="具体位置"
                          prop="recive_addr">
              <el-input v-model="addAddressForm.recive_addr"
                        placeholder="请输入具体位置">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="addAddressDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addAddress">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 显示协议pdf弹框 -->
    <el-dialog :visible.sync="rulePdfDialogVisible"
               title="服务协议">
      <iframe class="rule-pdf-iframe"
              src="../../../static/contract.pdf"
              frameborder="0"></iframe>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="rulePdfDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="rulePdfDialogVisible=false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import qs from 'qs'
import { ConfirmOrderApi } from '@/services/PurchaseMarket'
import { SendCodeApi } from '@/services/Public'
export default {
  data () {
    let validateBlank = (rule, value, callback) => {
      if (value.trim() === '') {
        return callback(new Error('不能输入空格'))
      } else {
        callback()
      }
    }
    return {
      // 添加地址弹框是否可见
      addAddressDialogVisible: false,
      // 添加地址表单对象
      addAddressForm: {
        recive_user: '',
        recive_addr: '',
        recive_phone: '',
        province: '',
        province_no: '',
        city: '',
        city_no: '',
        area: '',
        area_no: '',
        verify_code: ''
      },
      // 添加地址表单验证规则
      addAddressFormRules: {
        recive_user: [
          { required: true, message: '请输入收货人', trigger: 'blur' },
          { validator: validateBlank, trigger: 'blur' }
        ],
        recive_phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validateBlank, trigger: 'blur' }
        ],
        verify_code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { validator: validateBlank, trigger: 'blur' }
        ],
        recive_addr: [
          { required: true, message: '请输入具体位置', trigger: 'blur' },
          { validator: validateBlank, trigger: 'blur' }
        ]
      },
      // 选择地址弹框是否可见
      chooseAddressDialogVisible: false,
      // 已创建地址列表
      addressList: [],
      // 已选择的地址对象
      choosenAddressData: {

      },
      choosenAddressDataTemp: {

      },
      // 省市区数据
      addressOptions: [],
      provinceList: [],
      cityList: [],
      areaList: [],
      province: {},
      city: {},
      area: {},
      productCart: [],
      uuid: 1,
      // 收到的验证码
      verifyCode: '',
      // 创建订单对象
      submitOrderInfo: {
        recive_addr_id: ''
      },
      // 选中的地址id
      choosenAddressId: '',
      // 订单总额
      totalPrice: 0,
      // 运费
      transportFee: 0,
      // 应付金额
      actualPrice: 0,
      // 是否同意协议
      isAgree: false,
      // 协议pdf弹框是否可见
      rulePdfDialogVisible: false,
      // 获取验证码按钮是否禁用
      verifyCodeDisabled: false,
      // 验证码禁用倒计时时间
      verifyCodeTimeout: 60,
      // 验证码按钮文字
      verifyCodeBtnText: '获取验证码',
      // 验证码倒计时定时器id
      verifyCodeTimeoutId: 0
    }
  },
  methods: {
    // 地址数据
    getAddressData () {
      fetch(`/static/area.json`, {
        method: 'get',
        headers: {
          'Content-Type': 'application/json'
        }
      }).then(res => {
        return res.json()
      }).then(res => {
        this.addressOptions = res.data
        console.log(this.addressOptions, 'address options')
      })
    },
    chooseProvince (item) {
      this.cityList = item.children
      this.areaList = []
      this.city = {}
      this.area = {}
      this.addAddressForm.province = item.label
      this.addAddressForm.province_no = item.value
      this.addAddressForm.city = ''
      this.addAddressForm.city_no = ''
      this.addAddressForm.area = ''
      this.addAddressForm.area_no = ''
    },
    chooseCity (item) {
      this.areaList = item.children
      this.area = {}
      this.addAddressForm.city = item.label
      this.addAddressForm.city_no = item.value
      this.addAddressForm.area = ''
      this.addAddressForm.area_no = ''
    },
    chooseArea (item) {
      this.addAddressForm.area = item.label
      this.addAddressForm.area_no = item.value
    },
    // 获取地址列表
    getAddressList () {
      ConfirmOrderApi.getAddressList().then(res => {
        console.log(res, 'get address list')
        let data = res.data
        if (data) {
          this.addressList = data
          if (this.addressList.length > 0) {
            this.addressList.map((item) => {
              // item.choosen = false
              this.$set(item, 'choosen')
              item.phone = item.recive_phone.substring(0, 3) + '****' + item.recive_phone.substring(7, 11)
            })
            this.addressList[0].choosen = true
            this.choosenAddressId = this.addressList[0].recive_addr_id
            this.submitOrderInfo.recive_addr_id = this.addressList[0].recive_addr_id
            this.choosenAddressData = this.addressList[0]
          }
        }
      })
    },
    // 选择收货地址
    chooseAddress (item) {
      if (item.choosen) {
        this.addressList.map((addressItem) => {
          if (addressItem.recive_addr_id === this.choosenAddressId) addressItem.choosen = false
        })
        this.choosenAddressId = item.recive_addr_id
        this.choosenAddressDataTemp = item
      } else {
        this.choosenAddressId = ''
        this.choosenAddressDataTemp = {}
      }
      console.log(this.submitOrderInfo, item)
    },
    // 确定收货地址
    chooseReciveAddress () {
      if (this.choosenAddressId) {
        this.submitOrderInfo.recive_addr_id = this.choosenAddressId
        this.choosenAddressData = JSON.parse(JSON.stringify(this.choosenAddressDataTemp))
      } else if (this.choosenAddressId === '') {
        this.submitOrderInfo.recive_addr_id = ''
        this.choosenAddressData = {}
      }

      this.chooseAddressDialogVisible = false
    },
    // 选择省市区
    locationCascader (item) {
      console.log(item, 'change')
      if (item.length === 3) {
        this.getProvinceByNo()
      }
    },

    // 根据no获取省数据
    getProvinceByNo () {
      this.addressOptions.map(item => {
        if (item.value === this.addAddressForm.address[0]) {
          this.addAddressForm.province = item.label
          this.addAddressForm.province_no = item.value
          this.getCityByNo(item.children)
        }
      })
    },
    // 根据no获取市数据
    getCityByNo (cityList) {
      cityList.map(item => {
        if (item.value === this.addAddressForm.address[1]) {
          this.addAddressForm.city = item.label
          this.addAddressForm.city_no = item.value
          this.getAreaByNo(item.children)
        }
      })
    },
    // 根据no获取区数据
    getAreaByNo (areaList) {
      areaList.map(item => {
        if (item.value === this.addAddressForm.address[2]) {
          this.addAddressForm.area = item.label
          this.addAddressForm.area_no = item.value
        }
      })
    },
    // 新增并选择地址
    addAddress () {
      // console.log(this.addAddressForm)
      this.$refs.addressForm.validate(valid => {
        if (valid) {
          SendCodeApi.validateCode({
            data: {
              code: this.addAddressForm.verify_code,
              usage_code: 1
            }
          }).then(res => {
            console.log(res, 'validate code')
          })
          // if (this.verifyCode !== this.addAddressForm.verify_code) {
          // if (this.verifyCode === this.addAddressForm.verify_code) {
          //   this.$message.error('验证码错误')
          // } else if (this.addAddressForm.area_no === '') {
          //   this.$message.error('请选择收货地址')
          // } else {
          //   this.addAddressForm.uuid = this.uuid
          //   ConfirmOrderApi.createAddress({
          //     data: this.addAddressForm
          //   }).then(res => {
          //     console.log(res, 'create address')
          //     let data = res
          //     if (data.code === 1) {
          //       this.$message.success('创建成功')

          //       this.addAddressDialogVisible = false
          //       this.submitOrderInfo.recive_addr_id = data.recive_addr_id
          //       this.choosenAddressData = JSON.parse(JSON.stringify(this.addAddressForm))
          //       this.choosenAddressData.phone = this.choosenAddressData.recive_phone.substring(0, 3) + '****' + this.choosenAddressData.recive_phone.substring(7, 11)
          //     } else {
          //       this.$message.error(res.data.msg)
          //     }
          //     this.addAddressForm = {}
          //     this.$refs.addressForm.resetFields()
          //   })
          // }
        }
      })
    },
    // 获取验证码
    getVerifyCode () {
      if (this.addAddressForm.recive_phone && this.addAddressForm.recive_phone.trim() !== '') {
        this.verifyCodeDisabled = true
        this.verifyCodeInterval()
        SendCodeApi.sendCode({
          data: {
            phone: this.addAddressForm.recive_phone,
            usage_code: 1,
            template_no: 'industry-0006'
          }
        }).then(res => {
          if (res.code === 0) {

          }
        })
      } else {
        this.$message.error('请输入有效手机号')
      }
    },
    // 开始倒计时
    verifyCodeInterval () {
      let timeout = setInterval(() => {
        if (this.verifyCodeTimeout <= 0) {
          this.verifyCodeTimeout = 60
          this.verifyCodeDisabled = false
          this.verifyCodeBtnText = '获取验证码'
          clearInterval(this.verifyCodeTimeoutId)
        } else {
          this.verifyCodeTimeout--
          this.verifyCodeBtnText = '重新发送 ' + this.verifyCodeTimeout
        }
      }, 1000)
      this.verifyCodeTimeoutId = timeout
    },
    // 计算订单总额
    calOrderPrice () {
      this.totalPrice = 0
      this.actualPrice = 0
      this.productCart.map((item) => {
        this.totalPrice = +parseFloat(this.totalPrice) + +parseFloat((item.num * item.product_price)).toFixed(2)
      })
      this.totalPrice = parseFloat(this.totalPrice).toFixed(2)
      this.actualPrice = (parseFloat(this.totalPrice) + parseFloat(this.transportFee)).toFixed(2)
    },
    // 提交订单
    submitOrder () {
      this.submitOrderInfo.order_money = parseInt(this.totalPrice * 100)
      let productList = []
      this.productCart.map((item) => {
        productList.push({
          product_id: item.product_id,
          num: item.num
        })
      })

      this.submitOrderInfo.order_product = productList
      this.submitOrderInfo.uuid = this.uuid
      if (this.submitOrderInfo.recive_addr_id) {
        ConfirmOrderApi.createOrder({
          data: {
            order_money: this.submitOrderInfo.order_money,
            order_product: JSON.stringify(this.submitOrderInfo.order_product),
            recive_addr_id: this.submitOrderInfo.recive_addr_id
          }
        }).then(res => {
          console.log(res, 'create order')
          let data = res.data
          if (res.code === 0) {
            let orderInfo = {
              order_no: data.order_no,
              order_id: data.order_id,
              total_price: this.totalPrice
            }
            this.$router.push({
              path: '/payOrder',
              query: {
                orderInfo: JSON.stringify(orderInfo)
              }
            })
          } else {
            this.$message.error(res.msg)
          }
        }, err => {
          console.log(err)
        })
      } else {
        this.$message.warning('请选择地址')
      }
    }
  },
  created () {
    // this.productCart = JSON.parse(this.$route.query.productCart)
    let productCart = window.localStorage.getItem('productCart')
    if (productCart) {
      this.productCart = JSON.parse(productCart)
    }

    this.uuid = this.$route.query.uuid
    console.log(this.productCart)
    this.getAddressData()
    this.getAddressList()
    this.calOrderPrice()
  },
  mounted () {
  }
}
</script>
<style scoped lang='scss'>
@function p2vw($size) {
  @return ($size/1366) * 100vw;
}
.col-3 {
  width: 25%;
}
.col-4 {
  width: 33.33%;
}
/deep/ .el-step__head {
  &.is-process {
    .el-step__icon {
      width: 32px;
      height: 32px;
      color: #1890ff;
      border-color: #1890ff;
      font-size: 16px;
      font-weight: bold;
    }
  }
  &.is-wait {
    .el-step__icon {
      width: 32px;
      height: 32px;
      color: #bfbfbf;
      border-color: #bfbfbf;
      font-size: 16px;
      font-weight: bold;
    }
  }
  .el-step__line {
    top: 15px;
    background-color: #bfbfbf;
  }
}
/deep/ .el-step__main {
  .el-step__title {
    font-size: 14px;
    color: #666;
    font-weight: normal;
  }
}

.confirm-order-container {
  margin-bottom: 30px;
  p {
    margin: 0;
  }
  i {
    font-style: normal;
  }
  > h2 {
    height: 50px;
    line-height: 50px;
    padding-left: 20px;
    font-size: 16px;
    color: #1441b3;
    font-weight: normal;
    border-bottom: 1px solid #d9d9d9;
    margin: 0;
  }

  .step-container {
    width: 500px;
    margin: 20px auto 0;
  }
  /deep/ .el-dialog {
    box-shadow: 0 4px 4px rgba($color: #000000, $alpha: 0.2);
    -webkit-box-shadow: 0 4px 4px rgba($color: #000000, $alpha: 0.2);
  }
  .delivery-address-container {
    margin: 20px 0 30px;
    padding: 0 20px;

    h2 {
      font-size: 14px;
      color: #333;
      margin: 0;
      margin-bottom: 20px;
      span {
        font-size: 14px;
        color: #40a9ff;
        float: right;
        cursor: pointer;
      }
    }
    .delivery-address-info {
      border-bottom: 1px solid #e6e6e6;
      padding-bottom: 20px;
      p:not(:last-child) {
        margin-bottom: 12px;
        font-size: 14px;
        color: #333;
        i {
          color: #999;
        }
      }
      .choose-address {
        font-size: 14px;
        color: #1441b3;
        margin-top: 20px;
        cursor: pointer;
      }
    }
  }
  .product-info-container {
    padding: 0 20px;
    h2 {
      margin: 0;
      margin-bottom: 20px;
      font-size: 14px;
      color: #333;
    }
    .product-info-list {
      border-bottom: 1px solid #e6e6e6;
      .info-list-item {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
        img {
          width: 60px;
          height: 60px;
          border: 1px solid #bfbfbf;
          margin-right: 20px;
        }
        .product-detail-container {
          display: flex;
          flex-grow: 1;
          justify-content: space-between;
          align-items: center;
          .product-info {
            display: flex;
            flex-direction: column;
            justify-content: flex-start;
            &.flex-end {
              justify-content: flex-end;
            }
            .product-name {
              font-size: 14px;
              color: #333;
              margin-bottom: 12px;
            }
            .product-description {
              font-size: 12px;
              color: #999;
            }
            .product-num {
              font-size: 12px;
              color: #999;
              text-align: right;
            }
            .product-price {
              font-size: 18px;
              color: #ff4d4f;
              margin-bottom: 12px;
              font-weight: bold;
            }
          }
        }
      }
    }
  }
  .order-info-container {
    padding: 20px 20px 0;
    .order-info {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      &:last-child {
        border-bottom: 1px solid #e6e6e6;
        padding-bottom: 20px;
      }
      i {
        font-size: 14px;
        color: #999;
        text-align: right;
        margin-right: 100px;
      }
      span {
        font-size: 14px;
        color: #333;
        width: 100px;
        text-align: right;
        &.should-pay {
          font-size: 18px;
          color: #ff4d4f;
          font-weight: bold;
        }
      }
    }
    .total-price {
      margin-bottom: 12px;
    }
    .transport-fee {
      margin-bottom: 20px;
    }
  }
  .rule-container {
    display: flex;
    justify-content: flex-end;
    padding: 0 20px;
    margin-top: 40px;
    span {
      font-size: 14px;
      color: #666;
      i {
        color: #333;
      }
      a {
        cursor: pointer;
      }
    }
  }
  .submit-order-container {
    display: flex;
    margin-top: 20px;
    padding: 0 20px;
    justify-content: flex-end;
    button {
      width: 96px;
      height: 36px;
      border: 0;
      border-radius: 4px;
      background: #1890ff;
      color: #fff;
      font-size: 14px;
      line-height: 36px;
      cursor: pointer;
      &.disabled {
        background: #bfbfbf;
        color: #fff;
      }
    }
  }
  .choose-address-list {
    height: 350px;
    overflow: scroll;
    overflow-x: hidden;
    .choose-address-item {
      display: flex;
      align-items: center;
      padding: 0 20px;
      margin-bottom: 12px;
      .choose-checkbox {
        margin-right: 20px;
      }
      .address-info {
        display: flex;
        width: 384px;
        height: 76px;
        flex-direction: column;
        justify-content: center;
        border-radius: 4px;
        padding: 0 20px;
        border: 1px solid #bfbfbf;
        &.choosen {
          border: 1px solid #1890ff;
        }
        .recive-name {
          font-size: 14px;
          color: #333;
          margin-bottom: 12px;
          font-weight: bold;
          .recive-phone {
            font-weight: normal;
          }
        }
        .recive-address {
          color: #333;
          font-size: 12px;
        }
      }
    }
  }
  .add-address-form {
    .el-input-group {
      button.el-button {
        width: 120px;
        background-color: #fff;
        color: #1890ff;
        border: 0;
        border-radius: 0;
        font-size: 14px;
        &.disabled {
          color: #bfbfbf;
          // background: #bfbfbf;
        }
      }
    }
    /deep/ .get-verify-code {
      input {
        border-right: 0;
      }
    }
    .choose-location-cascader {
      width: 100%;
    }
  }
}
.rule-pdf-iframe {
  width: 100%;
  height: 500px;
}
</style>
